﻿using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using mattatz.Triangulation2DSystem;
using System.Threading;

public class MapController : MonoBehaviour {

    /// <summary>
    /// 背景网格
    /// </summary>
    public Mesh backGroundMesh;

    public MeshFilter backGroundMeshFilter;

    public MeshRenderer backGroundMeshRenderer;

    public GameObject lightController;

    private List<MapLayer> mapLayers=new List<MapLayer>();

    private List<Triangulation2D> triangulationList = new List<Triangulation2D>(20);

    public static MapConfigure mapConfigure;

    public static bool isBgLoadFinish=false;

    private bool isDataLoadFinish = false;

    private Thread convertThread;

    // Use this for initialization
    void Start () {
        initConfigure();

        init();
    }
	
	// Update is called once per frame
	void Update () {
	    if (Input.GetKeyDown(KeyCode.Space))
        {
            loadData(Resources.Load("json/xiang_gang.geo").ToString());
        }
        if (isDataLoadFinish)
        {
            foreach (Triangulation2D triangulation2D in triangulationList)
            {
                Mesh polygonMesh = triangulation2D.Build();

                GameObject gameobj = new GameObject();
                gameobj.transform.Rotate(new Vector3(0, 180, 90));
                gameobj.transform.Translate(new Vector3(0, 0, -1));
                gameobj.transform.parent = gameObject.transform;

                MeshFilter mf = gameobj.AddComponent<MeshFilter>();
                MeshRenderer mr = gameobj.AddComponent<MeshRenderer>();

                mf.mesh = polygonMesh;

                System.Random random = new System.Random();

                mr.material.color = new Color(random.Next(255),random.Next(255),random.Next(255));
            }

            isDataLoadFinish = false;
        }
	}
    public void init()
    {
        //初始化
        transform.position = new Vector3(0, 0, 0);

        initBackGround();

        isBgLoadFinish = true;

        lightController.SendMessage("LightInit");
    }

    /// <summary>
    /// 初始化配置
    /// </summary>
    private void initConfigure()
    {
        mapConfigure = new MapConfigure();
        mapConfigure.CameraDistance = 100;
    }

    /// <summary>
    /// 初始化背景
    /// </summary>
    private void initBackGround()
    {
        backGroundMeshFilter = GetComponent<MeshFilter>();

        backGroundMeshRenderer = GetComponent<MeshRenderer>();

        if (backGroundMeshFilter != null) {
            backGroundMesh = backGroundMeshFilter.mesh;
        }

        if (backGroundMesh == null)
        {
            backGroundMesh = new Mesh();
        }
        if (backGroundMeshFilter == null)
        {
            backGroundMeshFilter = gameObject.AddComponent<MeshFilter>();
            backGroundMeshFilter.mesh = backGroundMesh;
        }
        if (backGroundMeshRenderer == null)
        {
            backGroundMeshRenderer = gameObject.AddComponent<MeshRenderer>();
        }
        if (mapConfigure != null)
        {
            backGroundMesh.vertices = new Vector3[4] {new Vector3(0,0),new Vector3(mapConfigure.Width,0),
            new Vector3(mapConfigure.Width, mapConfigure.Height), new Vector3(0,mapConfigure.Height) };

            backGroundMesh.triangles = new int[] { 0, 1, 2, 2, 3, 0 };

            Texture texture = Texture2D.whiteTexture;

            backGroundMeshRenderer.material.mainTexture = texture;
        }
       
    }
    /// <summary>
    /// 加载地图数据
    /// </summary>
    /// <param name="str"></param>
    public void loadData(string str)
    {
        Guid guid = System.Guid.NewGuid();
        string tag = guid.ToString();
        long id = BitConverter.ToInt64(guid.ToByteArray(), 0);

        loadData(str, id, tag);
    }

    /// <summary>
    /// 加载地图数据
    /// </summary>
    public void loadData(string str,long id,string tag)
    {
        MapGeoDecode decode = new MapGeoDecode(str);

        decode.decode();

        MapLocation mapRightLocation = new MapLocation();
        mapRightLocation.Latitude = decode.MaxLat;
        mapRightLocation.Longitude = decode.MaxLon;

        MapLocation mapLeftLocation = new MapLocation();
        mapLeftLocation.Latitude = decode.MinLat;
        mapLeftLocation.Longitude = decode.MinLon;

        MapController.mapConfigure.MapRightBorder = mapRightLocation;
        MapController.mapConfigure.MapLeftBorder = mapLeftLocation;

        MapLayer mapLayer = new MapLayer();

        mapLayer.Id = id;
        mapLayer.Tag = tag;

        foreach (Features feature in decode.Geojson.Features)
        {
            if (feature.Geometry.Type.Equals(Geometry.Polygon)){
                foreach (JArray polygon in feature.Geometry.Coordinates)
                {
                    MapPolygon mapPolygon = new MapPolygon();

                    foreach (JArray polygonchild in polygon)
                    {
                        double lat = polygonchild[1].ToObject<double>();
                        double lon = polygonchild[0].ToObject<double>();

                        int[] xy = LocationTran.LatLon2XY(lat, lon);

                        MapLocation mapLocation = new MapLocation();
                        mapLocation.ScreenX = xy[0];
                        mapLocation.SceenY = xy[1];
                        mapLocation.Latitude = lat;
                        mapLocation.Longitude = lon;

                        mapPolygon.Datas.Add(mapLocation);
                    }

                    mapLayer.addMapPolygon(mapPolygon);
                }
            }
        }

        mapLayers.Add(mapLayer);

        convertMapObject();
    }

    /// <summary>
    /// 绘制数据
    /// </summary>
    private void convertMapObject()
    {
        convertThread = new Thread(threadstart=> {
            DateTime beforDT = System.DateTime.Now;

            foreach (MapLayer mapLayer in mapLayers)
            {
                foreach (MapObject mapObject in mapLayer.MapObjects)
                {
                    if (mapLayer.MapObjects.IndexOf(mapObject) == 1)
                    {
                        break;
                    }

                    if (mapObject.GetType() == typeof(MapPolygon))
                    {
                        MapPolygon mapPolygon = mapObject as MapPolygon;

                        List<Vector2> vector2List = new List<Vector2>(20);

                        foreach (MapLocation location in mapPolygon.Datas)
                        {
                            //坐标转换
                            Vector2 v2=  new Vector2(location.ScreenX, location.SceenY);

                            vector2List.Add(v2);
                        }

                        Polygon2D polygon2d = Polygon2D.Contour(vector2List.ToArray());

                        Triangulation2D triangulation2d = new Triangulation2D(polygon2d, 10f, 0.2f);

                        triangulationList.Add(triangulation2d);
                    }
                }
            }

            DateTime afterDT = System.DateTime.Now;

            TimeSpan ts = afterDT.Subtract(beforDT);

            Debug.Log("三角形转换总共花费"+ ts.TotalMilliseconds+"ms");

            isDataLoadFinish = true;
        });

        convertThread.Start();
    }
}
